<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>new操作符</title>
  </head>
  <body>
    <h3>new操作符</h3>
    <h4>new操作符，是JS内置的关键字，用于实例化一个对象。</h4>

    <script>
      function Fruits(name, price) {
        this.name = name;
        this.price = price;
        this.sayName = function () {
          console.log(`我是水果：${this.name}`);
        };
        this.sayPrice = function () {
          console.log(`${this.name}的价格：${this.price}...`);
        };
        return {
          sayName: () => {
            console.log(`我是水果：${this.name}`);
          },
          sayPrice: () => {
            console.log(`${this.name}的价格：${this.price}...`);
          },
        };
      }

      let banana = new Fruits("香蕉", 10);
      banana.sayName();
      banana.sayPrice();
      console.log(banana);

      function myNew(Fn, ...args) {
        let obj = Object.create(null);
        obj.__proto__ = Fn.prototype;
        let ret = Fn.call(obj, ...args);
        return ret instanceof Object ? ret : obj;
      }

      let banana2 = myNew(Fruits, "香蕉2号", 20);
      banana2.sayName();
      banana2.sayPrice();
      console.log(banana2);
    </script>
  </body>
</html>
